<template>
  <div class="anypay-apple-list-page">
    <div class="anypay-apple-page-header">
      <h1>聚合码牌管理</h1>
      <p>管理平台的所有聚合码牌，包括绑定APP、状态管理等功能</p>
    </div>

    <!-- 搜索区域 -->
    <div class="anypay-apple-card anypay-apple-mb-6">
      <a-card>
        <div class="search-container standard">
          <!-- 聚合码牌名称 -->
          <div class="search-field">
            <label class="search-label">聚合码牌名称:</label>
            <a-input
              v-model:value="searchForm.qrName"
              placeholder="请输入聚合码牌名称"
              class="search-input"
              allowClear
              @press-enter="handleSearch"
            />
          </div>

          <!-- 聚合码牌代码 -->
          <div class="search-field">
            <label class="search-label">聚合码牌代码:</label>
            <a-input
              v-model:value="searchForm.qrCode"
              placeholder="请输入聚合码牌代码"
              class="search-input"
              allowClear
              @press-enter="handleSearch"
            />
          </div>

          <!-- 绑定状态 -->
          <div class="search-field">
            <label class="search-label">绑定状态:</label>
            <a-select
              v-model:value="searchForm.bindStatus"
              placeholder="请选择绑定状态"
              class="search-select"
              allowClear
            >
              <a-select-option value="bound">已绑定</a-select-option>
              <a-select-option value="unbound">未绑定</a-select-option>
            </a-select>
          </div>

          <!-- 所属商户 -->
          <div class="search-field">
            <label class="search-label">所属商户:</label>
            <a-select
              v-model:value="searchForm.merchantId"
              placeholder="请选择商户"
              class="search-select-large"
              allowClear
              showSearch
              :filter-option="filterMerchantOption"
            >
              <a-select-option value="">全部</a-select-option>
              <a-select-option v-for="merchant in availableMerchants" :key="merchant.merchantId" :value="merchant.merchantId">
                {{ merchant.merchantName }}
              </a-select-option>
            </a-select>
          </div>

          <!-- 状态 -->
          <div class="search-field">
            <label class="search-label">状态:</label>
            <a-select
              v-model:value="searchForm.qrStatus"
              placeholder="请选择状态"
              class="search-select"
              allowClear
            >
              <a-select-option :value="1">启用</a-select-option>
              <a-select-option :value="0">停用</a-select-option>
            </a-select>
          </div>

          <!-- 操作按钮 -->
          <div class="search-actions">
            <a-button type="primary" @click="handleSearch" class="search-btn">
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button @click="handleReset" class="search-btn">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </div>
        </div>
      </a-card>
    </div>

    <!-- 数据表格区域 -->
    <div class="anypay-apple-card">
      <a-card>
        <div class="anypay-apple-table anypay-apple-toolbar">
          <AnyTable
            ref="qrCodeTable"
            :autoLoad="true"
            :dataLoader="loadQrCodeData"
            :tableColumns="tableColumns"
            :searchParams="searchParams"
            :tableScroll="{ x: 'max-content' }"
            tableRowKey="qrId"
            @loadComplete="handleLoadComplete"
          >
            <template #tableToolbar>
              <a-space :size="12">
                <a-button type="primary" @click="handleCreate">
                  <PlusOutlined /> 新增聚合码牌
                </a-button>
              </a-space>
            </template>
                    <template #tableCell="{ column, record }">
              <template v-if="column.key === 'qrStatus'">
                <a-tag :color="getQrStatusColor(record.qrStatus)">
                  {{ getQrStatusName(record.qrStatus) }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'boundApp'">
                <div v-if="record.boundAppId">
                  <a-tag color="green" style="margin-bottom: 4px;">
                    {{ getAppName(record.boundAppId) }}
                  </a-tag>
                  <br>
                  <span style="color: #666; font-size: 12px;">{{ record.boundAppId }}</span>
                </div>
                <span v-else style="color: #999;">未绑定</span>
              </template>
              <template v-else-if="column.key === 'merchantInfo'">
                <div>
                  <div style="font-weight: bold;">{{ record.merchantName }}</div>
                  <div style="color: #666; font-size: 12px;">{{ record.merchantId }}</div>
                </div>
              </template>
              <template v-else-if="column.key === 'bindTime'">
                <span v-if="record.bindTime">{{ formatTime(record.bindTime) }}</span>
                <span v-else style="color: #999;">未绑定</span>
              </template>
              <template v-else-if="column.key === 'qrCode'">
                <code style="background: #f5f5f5; padding: 2px 6px; border-radius: 3px; font-size: 12px;">
                  {{ record.qrCode }}
                </code>
              </template>
              <template v-else-if="column.key === 'action'">
                <div class="anypay-apple-actions">
                  <a-space>
                    <a-button type="link" @click="handleViewDetail(record)">查看</a-button>
                    <a-button type="link" @click="handleEdit(record)">编辑</a-button>
                    <a-button
                      type="link"
                      @click="handleBindApp(record)"
                      v-if="!record.boundAppId"
                    >
                      绑定APP
                    </a-button>
                    <a-dropdown placement="bottomRight">
                      <a-button type="link" size="small">
                        <MoreOutlined />
                        更多
                      </a-button>
                      <template #overlay>
                        <a-menu>
                          <a-menu-item
                            key="unbind"
                            @click="handleUnbindApp(record)"
                            v-if="record.boundAppId"
                          >
                            <DisconnectOutlined />
                            解绑APP
                          </a-menu-item>
                          <a-menu-item key="toggle" @click="handleToggleStatus(record)">
                            <SwapOutlined />
                            {{ record.qrStatus === 1 ? '停用' : '启用' }}
                          </a-menu-item>
                          <a-menu-divider />
                          <a-menu-item key="delete" @click="handleDelete(record)" style="color: #ff4d4f;">
                            <DeleteOutlined />
                            删除
                          </a-menu-item>
                        </a-menu>
                      </template>
                    </a-dropdown>
                  </a-space>
                </div>
              </template>
            </template>
          </AnyTable>
        </div>
      </a-card>
    </div>

    <!-- APP绑定对话框 -->
    <a-modal
      v-model:open="showBindDialog"
      title="绑定支付APP"
      @ok="handleConfirmBind"
      @cancel="handleCancelBind"
    >
      <div style="margin-bottom: 16px;">
        <strong>聚合码牌信息：</strong>{{ currentQr?.qrName }} ({{ currentQr?.qrCode }})
      </div>

      <a-form layout="vertical">
        <a-form-item label="选择要绑定的APP">
          <a-select
            v-model:value="selectedAppId"
            placeholder="请选择支付APP"
            style="width: 100%;"
            show-search
            :filter-option="filterAppOption"
          >
            <a-select-option
              v-for="app in availableApps"
              :key="app.appId"
              :value="app.appId"
            >
              <div>
                <div style="font-weight: bold;">{{ app.appName }}</div>
                <div style="color: #666; font-size: 12px;">
                  {{ getAppTypeName(app.appType) }} | {{ getMerchantName(app.merchantId) }}
                </div>
              </div>
            </a-select-option>
          </a-select>
        </a-form-item>

        <div v-if="selectedAppId" style="background: #f5f5f5; padding: 12px; border-radius: 6px;">
          <div style="font-size: 14px; font-weight: bold; margin-bottom: 8px;">APP详情：</div>
          <div v-if="selectedApp">
            <div><strong>APP名称：</strong>{{ selectedApp.appName }}</div>
            <div><strong>APP类型：</strong>{{ getAppTypeName(selectedApp.appType) }}</div>
            <div><strong>所属商户：</strong>{{ getMerchantName(selectedApp.merchantId) }}</div>
            <div><strong>连接模式：</strong>{{ getConnectModeName(selectedApp.connectMode) }}</div>
          </div>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { PlusOutlined, SearchOutlined, ReloadOutlined, MoreOutlined, DisconnectOutlined, SwapOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import {
  qrCodes,
  getQrStatusName,
  getQrStatusColor,
  formatTime,
  type QRCode
} from '@/mock'
import {
  appConfigs,
  getAppTypeName,
  getConnectModeName,
  getAppName as getAppNameFromConfigs,
  type AppConfig
} from '@/mock/appconfigs'
import { merchants, type Merchant } from '@/mock/merchants'
import AnyTable from '@/components/AnyTable.vue'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const dataSource = ref<QRCode[]>([])
const showBindDialog = ref(false)
const currentQr = ref<QRCode | null>(null)
const selectedAppId = ref('')

// 组件引用
const qrCodeTable = ref()

// 搜索表单
const searchForm = reactive({
  qrName: '',
  qrCode: '',
  bindStatus: undefined,
  merchantId: '',
  qrStatus: undefined
})

// 搜索参数
const searchParams = reactive<{
  qrName?: string
  qrCode?: string
  bindStatus?: string
  merchantId?: string
  qrStatus?: number
}>({})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

// 可用商户列表
const availableMerchants = ref<Merchant[]>([])

// 表格列定义
const tableColumns = [
  {
    title: '聚合码牌名称',
    dataIndex: 'qrName',
    key: 'qrName',
    width: 200,
    ellipsis: true
  },
  {
    title: '聚合码牌代码',
    key: 'qrCode',
    width: 150
  },
  {
    title: '状态',
    key: 'qrStatus',
    width: 80,
    align: 'center'
  },
  {
    title: '绑定APP',
    key: 'boundApp',
    width: 150
  },
  {
    title: '所属商户',
    key: 'merchantInfo',
    width: 180
  },
  {
    title: '有效期',
    dataIndex: 'validPeriod',
    key: 'validPeriod',
    width: 100,
    align: 'center',
    visible: false
  },
  {
    title: '绑定时间',
    key: 'bindTime',
    width: 120,
    align: 'center',
    visible: false
  },
  {
    title: '创建时间',
    dataIndex: 'createdTime',
    key: 'createdTime',
    width: 150
  },
  {
    title: '操作',
    key: 'action',
    width: 280,
    align: 'center',
    fixed: 'right'
  }
]

// 计算属性
const availableApps = computed(() => {
  return appConfigs.filter(app => {
    // 如果当前聚合码牌有关联商户，只显示该商户的APP
    if (currentQr.value?.merchantId) {
      return app.merchantId === currentQr.value.merchantId && app.status === 1
    }
    return app.status === 1
  })
})

const selectedApp = computed(() => {
  return availableApps.value.find(app => app.appId === selectedAppId.value)
})

// 数据加载函数
const loadQrCodeData = async (params: any) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    let filteredData = [...qrCodes]

    // 应用搜索筛选
    if (params.qrName) {
      filteredData = filteredData.filter(item =>
        item.qrName.toLowerCase().includes(params.qrName.toLowerCase())
      )
    }

    if (params.qrCode) {
      filteredData = filteredData.filter(item =>
        item.qrCode.toLowerCase().includes(params.qrCode.toLowerCase())
      )
    }

    if (params.bindStatus) {
      if (params.bindStatus === 'bound') {
        filteredData = filteredData.filter(item => !!item.boundAppId)
      } else {
        filteredData = filteredData.filter(item => !item.boundAppId)
      }
    }

    if (params.merchantId) {
      filteredData = filteredData.filter(item => item.merchantId === params.merchantId)
    }

    if (params.qrStatus !== undefined) {
      filteredData = filteredData.filter(item => item.qrStatus === params.qrStatus)
    }

    // 计算分页
    const startIndex = ((params.pageNumber || 1) - 1) * (params.pageSize || 10)
    const endIndex = startIndex + (params.pageSize || 10)
    const records = filteredData.slice(startIndex, endIndex)

    return {
      records,
      total: filteredData.length,
      pageNumber: params.pageNumber || 1,
      pageSize: params.pageSize || 10
    }
  } catch (error) {
    console.error('Failed to load QR code data:', error)
    return { records: [], total: 0, pageNumber: 1, pageSize: 10 }
  }
}

// 加载完成回调
const handleLoadComplete = () => {
  console.log('QR Code data loaded successfully')
}

// 方法实现
const handleCreate = () => {
  router.push('/development-test/qrcode-edit/create')
}

const handleViewDetail = (record: QRCode) => {
  router.push(`/development-test/qrcode-detail/${record.qrId}`)
}

const handleEdit = (record: QRCode) => {
  router.push(`/development-test/qrcode-edit/${record.qrId}`)
}

const handleDelete = (record: QRCode) => {
  message.success(`删除聚合码牌 ${record.qrName} 成功`)
  searchQrCodes()
}

const handleBindApp = (record: QRCode) => {
  currentQr.value = record
  selectedAppId.value = ''
  showBindDialog.value = true
}

const handleUnbindApp = (record: QRCode) => {
  record.boundAppId = undefined
  record.bindTime = undefined
  message.success(`解绑APP成功`)
}

const handleToggleStatus = (record: QRCode) => {
  const newStatus = record.qrStatus === 1 ? 0 : 1
  const action = newStatus === 1 ? '启用' : '停用'

  record.qrStatus = newStatus
  message.success(`${action}聚合码牌成功`)
}

const handleSearch = () => {
  // 清空之前的搜索参数
  Object.keys(searchParams).forEach(key => {
    delete (searchParams as any)[key]
  })

  // 只添加非空的搜索条件
  if (searchForm.qrName) {
    searchParams.qrName = searchForm.qrName
  }
  if (searchForm.qrCode) {
    searchParams.qrCode = searchForm.qrCode
  }
  if (searchForm.bindStatus) {
    searchParams.bindStatus = searchForm.bindStatus
  }
  if (searchForm.merchantId) {
    searchParams.merchantId = searchForm.merchantId
  }
  if (searchForm.qrStatus !== undefined) {
    searchParams.qrStatus = searchForm.qrStatus
  }

  searchQrCodes()
}

const handleReset = () => {
  // 清空搜索表单
  Object.assign(searchForm, {
    qrName: '',
    qrCode: '',
    bindStatus: undefined,
    merchantId: '',
    qrStatus: undefined
  })

  // 清空搜索参数
  Object.keys(searchParams).forEach(key => {
    delete (searchParams as any)[key]
  })

  searchQrCodes()
}

// 搜索二维码
const searchQrCodes = () => {
  qrCodeTable.value?.refreshTable(true)
}

const handleConfirmBind = () => {
  if (!selectedAppId.value) {
    message.error('请选择要绑定的APP')
    return
  }

  const app = selectedApp.value
  if (currentQr.value && app) {
    currentQr.value.boundAppId = app.appId
    currentQr.value.bindTime = new Date().toISOString().replace('T', ' ').substr(0, 19)

    message.success(`绑定APP ${app.appName} 成功`)
    showBindDialog.value = false
    selectedAppId.value = ''
  }
}

const handleCancelBind = () => {
  showBindDialog.value = false
  selectedAppId.value = ''
}

const filterAppOption = (input: string, option: any) => {
  const app = availableApps.value.find(app => app.appId === option.value)
  if (!app) return false

  const merchantName = getMerchantName(app.merchantId)
  return app.appName.toLowerCase().includes(input.toLowerCase()) ||
         merchantName.toLowerCase().includes(input.toLowerCase())
}

const filterMerchantOption = (input: string, option: any) => {
  const merchant = availableMerchants.value.find(m => m.merchantId === option.value)
  if (!merchant) return false
  return merchant.merchantName.toLowerCase().includes(input.toLowerCase())
}

const getChannelDisplayName = (channelCode: string) => {
  const channelMap: { [key: string]: string } = {
    WECHAT: '微信',
    ALIPAY: '支付宝',
    UNIONPAY: '银联',
    HUIFU: '汇付',
    FUIOU: '富友',
    DOUGONG: '斗拱'
  }
  return channelMap[channelCode] || channelCode
}

const getMerchantName = (merchantId: string) => {
  const merchant = merchants.find(m => m.merchantId === merchantId)
  return merchant ? merchant.merchantName : merchantId
}

const getConnectModeName = (mode: string) => {
  const modeMap: { [key: string]: string } = {
    'DIRECT': '直连',
    'INDIRECT': '间连'
  }
  return modeMap[mode] || mode
}

const getAppName = (appId: string) => {
  const app = appConfigs.find(app => app.appId === appId)
  return app ? app.appName : appId
}

// 加载商户列表
const loadMerchants = () => {
  availableMerchants.value = merchants.filter(m => m.status === 1)
}

// 组件挂载时加载数据
onMounted(() => {
  loadMerchants()
  // loadData 已由 AnyTable 的 autoLoad 处理
})
</script>

<style scoped>
@import '../common/list-page.css';

/* 对话框样式 */
.ant-modal .ant-modal-body {
  padding: 20px;
}

.ant-form-item {
  margin-bottom: 16px;
}

.ant-tag {
  margin-right: 4px;
  margin-bottom: 4px;
}
</style>